from flask import Flask
from flask_cors import CORS
from app.models.mysql_db import db
from app.models.mongodb import init_mongodb
from app.utils.logger import init_logger, get_logger
import os

# 初始化模块级日志记录器
logger = get_logger(__name__)

def create_app(config_object='app.config.Config'):
    """创建并配置Flask应用实例"""
    logger.info("开始创建Flask应用...")
    app = Flask(__name__)
    
    # 从配置文件加载配置
    app.config.from_object(config_object)
    logger.info("已加载配置文件")
    
    # 配置跨域 - 增强版
    CORS(app, 
        resources={r"/*": {"origins": "*"}},  # 允许所有资源的所有来源访问
        methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],  # 明确允许的HTTP方法
        allow_headers=["Content-Type", "Authorization", "X-Requested-With", "X-JWT-Bypass", "X-CSRFToken"], # 明确允许的请求头
        expose_headers=["Content-Disposition"],   # 允许前端访问的响应头
        supports_credentials=True)                # 允许凭据
    logger.info("已配置CORS基础设置")
    
    # 添加OPTIONS请求处理器 - 解决预检请求问题
    @app.route('/<path:path>', methods=['OPTIONS'])
    def options_handler(path):
        response = app.make_default_options_response()
        # 允许所有来源
        response.headers.add('Access-Control-Allow-Origin', '*')
        # 允许的方法
        response.headers.add('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH')
        # 允许的请求头
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, X-JWT-Bypass, X-CSRFToken')
        # 允许凭证
        response.headers.add('Access-Control-Allow-Credentials', 'true')
        # 缓存预检请求结果时间（秒）
        response.headers.add('Access-Control-Max-Age', '3600')
        return response
    
    logger.info("已配置OPTIONS请求处理器")

    # 初始化日志
    init_logger(app)
    logger.info("已初始化日志系统")
    
    # 初始化数据库
    db.init_app(app)
    logger.info("已初始化MySQL数据库")
    init_mongodb(app)
    logger.info("已初始化MongoDB数据库")
    
    # 首先在应用上下文中创建所有表
    with app.app_context():
        logger.info("开始创建数据库表...")
        db.create_all()
        logger.info("数据库表创建/更新完成")
    
    # 在创建表之后再注册蓝图，避免循环导入问题
    logger.info("开始注册蓝图...")
    
    # 注册蓝图
    from app.routes.api_data import data_bp
    from app.routes.api_device import device_bp
    from app.routes.api_auth import auth_bp
    from app.routes.api_user import user_bp
    from app.routes.api_dashboard import dashboard_bp
    from app.routes.api_device_analysis import device_analysis_bp
    from app.routes.api_debug import debug_bp
    from app.routes.api_adapter import register_api_adapter

    app.register_blueprint(data_bp)
    logger.info("已注册data_bp蓝图")
    app.register_blueprint(device_bp)
    logger.info("已注册device_bp蓝图")
    app.register_blueprint(auth_bp)
    logger.info("已注册auth_bp蓝图")
    app.register_blueprint(user_bp)
    logger.info("已注册user_bp蓝图")
    app.register_blueprint(dashboard_bp)
    logger.info("已注册dashboard_bp蓝图")
    app.register_blueprint(device_analysis_bp)
    logger.info("已注册device_analysis_bp蓝图")
    app.register_blueprint(debug_bp)
    logger.info("已注册debug_bp蓝图")
    
    # 注册API适配器蓝图
    register_api_adapter(app)
    logger.info("已注册API适配器蓝图")
    
    return app
